package com.perceptivesoftware.licensing.server.rpc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.perceptivesoftware.licensing.client.dto.UserInitialDTO;
import com.perceptivesoftware.licensing.client.rpc.SessionService;
import com.perceptivesoftware.licensing.server.user.UserAlreadyLoggedInException;
import com.perceptivesoftware.licensing.server.user.UserNotLoggedInException;
import com.perceptivesoftware.licensing.server.util.SessionServiceUtil;
import com.perceptivesoftware.licensing.server.util.UserUtil;

@Transactional
@Service("sessionService")
public class SessionServiceImpl implements SessionService // NO_UCD
{
	@Autowired
	SessionServiceUtil sessionServiceUtil;
	@Autowired
	UserUtil userUtil;

	@Override
	public void logoff(final boolean isTimeout)
	{
		sessionServiceUtil.logout();
	}

	@Override
	public UserInitialDTO initialLogon()
	{
		try
		{
			return sessionServiceUtil.logon();
		}
		catch (final UserAlreadyLoggedInException e)
		{
			final UserInitialDTO errorDTO = new UserInitialDTO(null);
			errorDTO.setErrorMessage("You are already logged in in another session.");
			return errorDTO;
		}
		catch (final NoUservalForUserException e)
		{
			final UserInitialDTO errorDTO = new UserInitialDTO(null);
			errorDTO.setErrorMessage("No users are configured for your authentication.");
			return errorDTO;
		}
	}

	@Override
	public UserInitialDTO loadUserDTO(String optionalSessionID)
	{
		try
		{
			return sessionServiceUtil.loadUserDTO(optionalSessionID);
		}
		catch (final UserNotLoggedInException e)
		{
			final UserInitialDTO uid = new UserInitialDTO(null);
			uid.setErrorMessage("User not logged in");
			return uid;
		}
		catch (final UserNotAuthenticatedException e)
		{
			final UserInitialDTO uid = new UserInitialDTO(null);
			uid.setErrorMessage("User not authenticated");
			return uid;
		}
	}

	@Override
	public String heartbeat(String sessionID)
	{
		return sessionServiceUtil.heartbeat(sessionID);
	}
}